<template>
  <div class="erp-finance-report">
    <el-card shadow="never">
      <template #header>
        <div class="erp-finance-report__header">
          <span>财务报表</span>
        </div>
      </template>
      <el-tabs v-model="activeTab" @tab-change="onTabChange">
        <el-tab-pane label="凭证列表" name="voucher">
          <el-form :inline="true" class="erp-finance-report__search" @submit.prevent>
            <el-form-item label="凭证号">
              <el-input v-model="query.voucher.voucherNo" clearable placeholder="支持模糊" />
            </el-form-item>
            <el-form-item label="凭证日期">
              <el-date-picker
                v-model="query.voucher.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始"
                end-placeholder="结束"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item label="单据类型">
              <el-select v-model="query.voucher.billType" placeholder="全部" clearable>
                <el-option value="PO_IN" label="采购入库" />
                <el-option value="SO_OUT" label="销售出库" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="small" @click="loadVoucher">查询</el-button>
              <el-button size="small" @click="resetVoucher">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="voucherList" size="small" style="width: 100%">
            <el-table-column prop="voucherNo" label="凭证号" min-width="120" />
            <el-table-column prop="voucherDate" label="凭证日期" min-width="120" />
            <el-table-column prop="billType" label="单据类型" min-width="120">
              <template #default="{ row }">
                <el-tag v-if="row.billType === 'PO_IN'" type="primary">采购入库</el-tag>
                <el-tag v-else-if="row.billType === 'SO_OUT'" type="success">销售出库</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="billNo" label="单据号" min-width="140" />
            <el-table-column prop="status" label="状态" min-width="100">
              <template #default="{ row }">
                <el-tag v-if="row.status === 'POSTED'" type="success">已过账</el-tag>
                <el-tag v-else type="info">{{ row.status }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="120">
              <template #default="{ row }">
                <el-button link type="primary" size="small" @click="viewVoucherEntries(row)">查看明细</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="erp-finance-report__pagination">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="voucherTotal"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="voucherPageSize"
              :current-page="voucherPageNum"
              @size-change="onVoucherSizeChange"
              @current-change="onVoucherPageChange"
            />
          </div>
        </el-tab-pane>
        <el-tab-pane label="科目余额" name="balance">
          <el-form :inline="true" class="erp-finance-report__search" @submit.prevent>
            <el-form-item label="科目">
              <el-input v-model="query.balance.accountId" clearable placeholder="科目ID" />
            </el-form-item>
            <el-form-item label="日期范围">
              <el-date-picker
                v-model="query.balance.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始"
                end-placeholder="结束"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="small" @click="loadBalance">查询</el-button>
              <el-button size="small" @click="resetBalance">重置</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="balanceList" size="small" style="width: 100%">
            <el-table-column prop="accountId" label="科目ID" min-width="120" />
            <el-table-column prop="debitTotal" label="借方合计" min-width="120" />
            <el-table-column prop="creditTotal" label="贷方合计" min-width="120" />
            <el-table-column prop="balance" label="余额" min-width="120" />
            <el-table-column prop="balanceDirection" label="余额方向" min-width="120">
              <template #default="{ row }">
                <el-tag v-if="row.balanceDirection === 'DEBIT'" type="success">借方</el-tag>
                <el-tag v-else-if="row.balanceDirection === 'CREDIT'" type="warning">贷方</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 凭证明细对话框 -->
    <el-dialog v-model="entriesDialogVisible" title="凭证明细" width="800px">
      <el-table :data="voucherEntries" size="small" style="width: 100%">
        <el-table-column prop="entryNo" label="分录号" min-width="80" />
        <el-table-column prop="accountId" label="科目ID" min-width="120" />
        <el-table-column prop="dcFlag" label="借贷方向" min-width="100">
          <template #default="{ row }">
            <el-tag v-if="row.dcFlag === 'DEBIT'" type="success">借方</el-tag>
            <el-tag v-else-if="row.dcFlag === 'CREDIT'" type="warning">贷方</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" min-width="120" />
        <el-table-column prop="summary" label="摘要" min-width="200" />
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { pageFinanceVoucher, getVoucherEntries, getAccountBalance } from '@/api/erp/report'
import { ElMessage } from 'element-plus'

const activeTab = ref('voucher')

// 凭证列表
const voucherList = ref<any[]>([])
const voucherTotal = ref(0)
const voucherPageNum = ref(1)
const voucherPageSize = ref(10)
const query = reactive({
  voucher: {
    voucherNo: '',
    dateRange: [] as string[],
    billType: ''
  },
  balance: {
    accountId: '',
    dateRange: [] as string[]
  }
})

// 科目余额
const balanceList = ref<any[]>([])

// 凭证明细
const entriesDialogVisible = ref(false)
const voucherEntries = ref<any[]>([])

const loadVoucher = async () => {
  const res = await pageFinanceVoucher({
    pageNum: voucherPageNum.value,
    pageSize: voucherPageSize.value,
    voucherNo: query.voucher.voucherNo || undefined,
    startDate: Array.isArray(query.voucher.dateRange) && query.voucher.dateRange.length === 2 ? query.voucher.dateRange[0] : undefined,
    endDate: Array.isArray(query.voucher.dateRange) && query.voucher.dateRange.length === 2 ? query.voucher.dateRange[1] : undefined,
    billType: query.voucher.billType || undefined
  })
  voucherList.value = res?.data?.records || []
  voucherTotal.value = res?.data?.total || 0
}

const loadBalance = async () => {
  const res = await getAccountBalance({
    accountId: query.balance.accountId || undefined,
    startDate: Array.isArray(query.balance.dateRange) && query.balance.dateRange.length === 2 ? query.balance.dateRange[0] : undefined,
    endDate: Array.isArray(query.balance.dateRange) && query.balance.dateRange.length === 2 ? query.balance.dateRange[1] : undefined
  })
  balanceList.value = res?.data || []
}

const viewVoucherEntries = async (row: any) => {
  try {
    const res = await getVoucherEntries(String(row.voucherId))
    voucherEntries.value = res?.data || []
    entriesDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取凭证明细失败')
  }
}

const onTabChange = (tab: string) => {
  if (tab === 'voucher') {
    loadVoucher()
  } else if (tab === 'balance') {
    loadBalance()
  }
}

const resetVoucher = () => {
  query.voucher.voucherNo = ''
  query.voucher.dateRange = []
  query.voucher.billType = ''
  voucherPageNum.value = 1
  loadVoucher()
}

const resetBalance = () => {
  query.balance.accountId = ''
  query.balance.dateRange = []
  loadBalance()
}

const onVoucherPageChange = (p: number) => {
  voucherPageNum.value = p
  loadVoucher()
}

const onVoucherSizeChange = (s: number) => {
  voucherPageSize.value = s
  voucherPageNum.value = 1
  loadVoucher()
}

onMounted(() => {
  loadVoucher()
})
</script>

<style scoped lang="scss">
.erp-finance-report {
  &__header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  &__pagination {
    margin-top: 12px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

